#!/usr/bin/env bash

# Set Some Variables
IFLAG='/etc/columnstore/container-initialized'
MCS_INSTALL_BIN='/usr/bin'
LOG_PREFIX='/var/log/mariadb/columnstore'
CLUSTER_SIZE=$(mcsGetConfig PrimitiveServers Count)
PFLAG='/etc/columnstore/container-provisioned'
CMAPI_KEY="${CMAPI_KEY:-somekey123}"
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

# Intialize Container If Necessary
if [[ ! -e ${IFLAG} ]]; then
    if ! "${MCS_INSTALL_BIN}"/columnstore-init &>"${LOG_PREFIX}"/columnstore-init.log; then
        echo "ERROR: During Initialization."
        exit 1
    fi
fi

# Verify S3 Connectivity
if [[ "${USE_S3_STORAGE}" == true ]]; then
    if testS3Connection &>/dev/null; then
        echo -e "Verifying S3 Connectivity... ${GREEN}done${NC}"
    else
        echo -e "Verifying S3 Connectivity... ${RED}fail${NC}"
        exit 1
    fi
fi

# Start CMAPI
touch "${LOG_PREFIX}"/cmapi_server.log && chmod 666 "${LOG_PREFIX}"/cmapi_server.log
cd /usr/share/columnstore/cmapi || exit
if PYTHONPATH=/usr/share/columnstore/cmapi/deps /usr/share/columnstore/cmapi/python/bin/python3 -m cmapi_server &>"${LOG_PREFIX}"/cmapi_server.log & then
    echo -e "Starting Cluster Manager API... ${GREEN}done${NC}"
else
    echo -e "Starting Cluster Manager API... ${RED}fail${NC}"
    exit 1
fi

# Start Columnstore (If This Is Single Node)
if [[ -e "${PFLAG}" && "${CLUSTER_SIZE}" -eq 1 ]]; then
    if mcs cluster start &>/dev/null; then
        echo -e "Starting ColumnStore... ${GREEN}done${NC}"
    else
        echo -e "Starting ColumnStore... ${RED}fail${NC}"
        exit 1
    fi
fi

# Start MariaDB
if ! mariadb-admin ping &>/dev/null; then
    if  /etc/init.d/mariadb start &>/dev/null & then
        echo -e "Starting MariaDB Server... ${GREEN}done${NC}"
    else
        echo -e "Starting MariaDB Server... ${RED}fail${NC}"
        exit 1
    fi
    sleep 5
fi

exit 0
